package vikaa.timelinepackage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.vikaa.wowo.widget.MyGallery;

import vikaa.bean.Member_item;
import vikaa.tools.DialogService;
import vikaa.tools.HttpUtil;
import vikaa.tools.StringUtils;
import vikaa.tools.ValueClass;
import vikaa.ui.Mywowo;
import vikaa.ui.WeiboFriendChoose;
import vikaa.wowo.R;
import vikaa.wowo.cache.AuthoSharePreference;
import vikaa.wowo.cache.SpaceListSqlStoragePrivate;
import vikaa.wowo.cache.UserInfoSharePreference;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class TimelineSettings extends Activity implements OnClickListener,OnCheckedChangeListener{
	private LinearLayout backBtn;
	private RelativeLayout nameBtn;
	private RelativeLayout myweiboBtn;
	private RelativeLayout fdweiboBtn;
	private RelativeLayout smsBtn;
	private RelativeLayout photoBtn;
	private CheckBox broadCb;
	private CheckBox privateCb;
	private ImageView logoutBtn;
	private EditText nameEdt;
	private TextView broadTv;
	private TextView privateTv;
	public static String space_id;
	public static String weibo_uid;
	public static String role;
	private String spacename;
	private String state;
	private ArrayList<Member_item> list = new ArrayList<Member_item>();
	private MyGallery gallery;
	private AdapterGallleryManager adapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.timeline_settings);
		space_id = getIntent().getExtras().getString("space_id");
		weibo_uid = AuthoSharePreference.getUid(TimelineSettings.this);
		role = getIntent().getExtras().getString("role");
		state = getIntent().getExtras().getString("state");
		initview();
		initManagerMember();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN ){     
			Intent in = new Intent();
			Bundle b = new Bundle();
			b.putString("spacename", spacename);
			b.putString("state", state);
			b.putInt("finish", 0);
			in.putExtras(b);
			setResult(RESULT_OK, in);	
	        finish();  
	        return true;     
	    }  
	    return super.onKeyDown(keyCode, event); 
	}
	
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.backBtn:
			Intent in = new Intent();
			Bundle b = new Bundle();
			b.putString("spacename", spacename);
			b.putString("state", state);
			b.putInt("finish", 0);
			in.putExtras(b);
			setResult(RESULT_OK, in);
			finish();
			break;
		case R.id.scv:
			nameEdt.clearFocus();
			DialogService.hideSoftKeypad(TimelineSettings.this);
			break;
		case R.id.myweiboRl:
			Intent i = new Intent(TimelineSettings.this,TimelineImportWeibo.class);
			i.putExtra("space_id", space_id);
			i.putExtra("weibo_uid", weibo_uid);
			i.putExtra("role",role);
			startActivity(i);
			break;
		case R.id.friendweiboRl:
			WeiboFriendChoose.setflag = true;
			Intent i1 = new Intent(TimelineSettings.this,WeiboFriendChoose.class);
			startActivity(i1);
			break;
		case R.id.smsRl:
			break;
		case R.id.photoRl:
			Intent i11 = new Intent(TimelineSettings.this,TimelineGallery.class);
			i11.putExtra("space_id", space_id);
			i11.putExtra("role",role);
			startActivity(i11);
			break;
		case R.id.logoutBtn:
			new AlertDialog.Builder(TimelineSettings.this).setTitle(getString(R.string.tip)).setMessage(getString(R.string.msg_logout))
			.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					new WowoExitThread().start();
				}
			}).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
				}
			}).show();
			break;
		}
	}
	
	private void initview(){
		backBtn = (LinearLayout)findViewById(R.id.backBtn);
		backBtn.setOnClickListener(this);
		nameBtn = (RelativeLayout)findViewById(R.id.nameRl);
		nameBtn.setOnClickListener(this);
		myweiboBtn = (RelativeLayout)findViewById(R.id.myweiboRl);
		myweiboBtn.setOnClickListener(this);
		fdweiboBtn = (RelativeLayout)findViewById(R.id.friendweiboRl);
		fdweiboBtn.setOnClickListener(this);
		smsBtn = (RelativeLayout)findViewById(R.id.smsRl);
		smsBtn.setOnClickListener(this);
		photoBtn = (RelativeLayout)findViewById(R.id.photoRl);
		photoBtn.setOnClickListener(this);
		broadCb = (CheckBox)findViewById(R.id.broadCB);
		broadCb.setOnCheckedChangeListener(this);
		privateCb = (CheckBox)findViewById(R.id.privateCB);
		privateCb.setChecked(state.equals("1")?true:false);
		privateCb.setOnCheckedChangeListener(this);
		logoutBtn = (ImageView)findViewById(R.id.logoutBtn);
		logoutBtn.setOnClickListener(this);
		nameEdt = (EditText)findViewById(R.id.nameTv);
		spacename = Timeline.space_name;
		nameEdt.setText(spacename);
		nameEdt.addTextChangedListener(mNicknameWatcher);
		
		if(Integer.valueOf(role) == ValueClass.ROLE_CREATOR ){
			nameEdt.setFocusable(true);
			nameEdt.setFocusableInTouchMode(true);
		}
		nameEdt.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus){
				}
				else{
					String value = nameEdt.getText().toString();
					value = StringUtils.spaceEdit(value);
					if(!(value.equals(spacename)) && !StringUtils.isEmpty(value)){
						new UpdateSettingsThread("spacename", value).start();
					}
				}
			}
		});
		if(Integer.valueOf(role) == ValueClass.ROLE_CREATOR || Integer.valueOf(role) == ValueClass.ROLE_ADMIN){
			RelativeLayout priRl = (RelativeLayout)findViewById(R.id.privateRl);
			TextView pmsgTv = (TextView)findViewById(R.id.privatemsgTv);
			TextView setMsg = (TextView)findViewById(R.id.settingMSG);
			priRl.setVisibility(View.VISIBLE);
			pmsgTv.setVisibility(View.VISIBLE);
			setMsg.setVisibility(View.VISIBLE);
		}
		broadTv = (TextView)findViewById(R.id.boradcastTv);
		privateTv = (TextView)findViewById(R.id.privateTv);
		privateTv.setVisibility(View.GONE);
		LinearLayout scv = (LinearLayout)findViewById(R.id.scv);
		scv.setOnClickListener(this);
	}
	private void initMyGallery(){
		gallery = (MyGallery)findViewById(R.id.myGallery);
		adapter = new AdapterGallleryManager(TimelineSettings.this,list,getLayoutInflater());
		gallery.setAdapter(adapter);
		/*gallery.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				startActivity(new Intent(TimelineSettings.this,WowoMember.class));
			}
		});*/
	}
	TextWatcher mNicknameWatcher = new TextWatcher() {
        private CharSequence temp;
        private int editStart ;
        private int editEnd ;
        public void beforeTextChanged(CharSequence s, int arg1, int arg2,
                int arg3) {
            temp = s;
        }
       
        public void onTextChanged(CharSequence s, int arg1, int arg2,
                int arg3) {
        }
       
        public void afterTextChanged(Editable s) {
            editStart = nameEdt.getSelectionStart();
            editEnd = nameEdt.getSelectionEnd();
            if (temp.length() > 16) {
                s.delete(editStart-1, editEnd);
                int tempSelection = editStart;
                nameEdt.setText(s);
                nameEdt.setSelection(tempSelection);
            }
        }
    };
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch(buttonView.getId()){
		case R.id.privateCB:
			if(isChecked){
				privateTv.setText(getString(R.string.private_on));
				state = "1";
				new UpdateSettingsThread("state", state).start();
			}else{
				privateTv.setText(getString(R.string.private_off));
				new AlertDialog.Builder(TimelineSettings.this).setTitle(getString(R.string.tip)).setMessage(getString(R.string.set_private_msg))
				.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						privateCb.setChecked(false);
						state = "0";
						new UpdateSettingsThread("state", state).start();
					}
				}).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						//privateCb.setChecked(true);
					}
				}).show();
			}
			break;
		case R.id.broadCB:
			if(isChecked){
				broadTv.setText(getString(R.string.close));
			}else{
				broadTv.setText(getString(R.string.open));
			}
			break;
		}
	}
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if(ev.getAction() == MotionEvent.ACTION_MOVE){
			nameEdt.clearFocus();
			DialogService.hideSoftKeypad(TimelineSettings.this);
		}
		return super.dispatchTouchEvent(ev);
	}
	Handler mhandler = new Handler(){
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 1:
				spacename = nameEdt.getText().toString();
				SpaceListSqlStoragePrivate.updateSpaceName(space_id, spacename, TimelineSettings.this);
				SpaceListSqlStoragePrivate.updateState(space_id, state, TimelineSettings.this);
				Toast.makeText(TimelineSettings.this, "更新成功", Toast.LENGTH_SHORT).show();
				break;
			case 2://exit wowo
				//Timeline.isfinish = true;
				Intent in = new Intent();
				Bundle b = new Bundle();
				b.putString("spacename", spacename);
				b.putString("state", state);
				b.putInt("finish", 1);
				in.putExtras(b);
				setResult(RESULT_OK, in);
				finish();
				/*Mywowo.isrefresh = true;
				Mywowo.wowoexit = true;
				Intent i = new Intent(TimelineSettings.this,Mywowo.class);
				i.putExtra("uid", UserInfoSharePreference.getUid(TimelineSettings.this));
				startActivity(i);*/
				//SpaceListSqlStoragePrivate.dropSpaceList(TimelineSettings.this);
				break;
			case 3:
				if(msg.obj != null){
					Toast.makeText(TimelineSettings.this, (String)msg.obj , Toast.LENGTH_SHORT).show();
				}
				else
					Toast.makeText(TimelineSettings.this, R.string.server_crash, Toast.LENGTH_SHORT).show();
				break;
			case 4:
				Toast.makeText(TimelineSettings.this, R.string.network_crash, Toast.LENGTH_SHORT).show();
				break;
			case 5:
				if(msg.obj != null){
					ArrayList<Member_item> strings = (ArrayList<Member_item>) msg.obj;
					if(!strings.isEmpty()){
						list.addAll(strings);
						initMyGallery();
					}
				}
				break;
			}
		}
    };
    private void initManagerMember(){
		new Thread(new Runnable() {
			public void run() {
				ArrayList<Member_item> templist = new ArrayList<Member_item>();
				Map<String,String> map = new HashMap<String, String>();
				map.put("space_id", TimelineSettings.space_id);
				map.put("page", "1");
				try {
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL + "space/managers", map));
					if(jsonObj.getString("result").equals("1")){
						JSONArray info = jsonObj.getJSONArray("info");
						for(int i=0;i<info.length();i++){
							Member_item item = new Member_item();
							item.setUid(info.getJSONObject(i).getString("uid"));
							item.setCredits(info.getJSONObject(i).getString("credits"));
							item.setDomain(info.getJSONObject(i).getString("domain"));
							item.setOauth_type(info.getJSONObject(i).getString("oauth_type"));
							item.setProfile_image_url(info.getJSONObject(i).getString("profile_image_url"));
							item.setScreen_name(info.getJSONObject(i).getString("screen_name"));
							item.setSina_id(info.getJSONObject(i).getString("sina_id"));
							templist.add(item);
						}	
						/*Member_item item = new Member_item();
						item.setProfile_image_url("plus");
						item.setUid("0");
						item.setCredits("0");
						item.setDomain("0");
						item.setOauth_type("0");
						item.setScreen_name("0");
						item.setSina_id("0");
						templist.add(item);*/
						Message msg = mhandler.obtainMessage(5);
						msg.obj = templist;
						msg.sendToTarget();
					}
					else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}else
					{	
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				}catch (JSONException e) {
					
				}
			}
		}).start();
	}
	class UpdateSettingsThread extends Thread{
		private String value;
		private String key;
		private boolean isrun = true;
		private UpdateSettingsThread(String key,String value){
			this.value = value;
			this.key = key;
		}
		@Override
		public void run() {
			while(isrun){
				isrun = false;
				try{
					Map<String,String> map = new HashMap<String, String>() ;
					map.put(key, value);
					map.put("space_id", Timeline.space_id);
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+"space/edit", map));
					if(jsonObj.getString("result").equals("1")){
						Message msg = mhandler.obtainMessage(1);
						msg.sendToTarget();						
					}
					else if (jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}else{
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	class WowoExitThread extends Thread{
		private boolean isrun = true;
		@Override
		public void run() {
			while(isrun){
				isrun = false;
				try{
					Map<String,String> map = new HashMap<String, String>() ;
					map.put("space_id", Timeline.space_id);
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+"space/exit", map));
					if(jsonObj.getString("result").equals("1")){
						Message msg = mhandler.obtainMessage(2);
						msg.sendToTarget();						
					}
					else if (jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}else{
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
}
